import os.path
import time
import threading
from libs.comps.common.component import manager , TComponentManager , TComponent
import schedule
from libs.utils.mqtt_utils import TMqtt

class TCompMqtt( TComponent):
    def __init__(self, _manager):
        super().__init__(_manager)
        self._client :TMqtt = None
        self.subTopics =[]
    @property
    def brokerSettings(self):
        res={
            "host":"",
            "port":1883,
            "uid":"",
            "pwd":""
        }
        try:
            if 'brokerSettings' in self.compSettings.keys():
                res.update(self.compSettings['brokerSettings'])
        except Exception as er:
            self.manager.log(self , er)
        return res
    @property
    def mqttClient(self):
        try:
            if self._client==None:
                host = self.brokerSettings['host']
                port = self.brokerSettings['port']
                uid = self.brokerSettings['uid']
                pwd = self.brokerSettings['pwd']
                self._client = TMqtt.newMqtt(host , port, uid , pwd , self.subTopics , self.onMessage)
        except Exception as er:
            self.manager.log(self , er)
        return self._client
    def onMessage(self, message, mqttClient):
        try:
            pass
        except Exception as er:
            self.manager(self, er)
    def init(self):
        try:
            pass
        except Exception as er:
            self.manager.log(self , er)
    def serviceHandler(self):
        try:
            super().serviceHandler()
        except Exception as erBrfore:
            self.manager.log(self, erBrfore)
    def beforeStartService(self):
        try:
            super().beforeStartService()
            self.init()
        except Exception as er:
            self.manager.log(self, er)
    def startService(self):
        try:
            if not self.running:
                try:
                    self.beforeStartService()
                except Exception as erBrfore:
                    self.manager.log(self, erBrfore)
                self.serviceThread = threading.Thread(target=self.serviceHandler , daemon=True)
                self.running = True
                self.serviceThread.start()
        except Exception as er:
            self.manager.log(self, er)
    def stopService(self):
        try:
            self.running = False
            if self._client!=None:
                self._client.disconnect()
                self._client = None
        except Exception as er:
            self.manager.log(self, er)
